<template>
  <div class="Progress-neg-container">
    <div class="title">Traveller Type</div>

    <!-- 等待状态：初始加载时显示加载动画 -->
    <div v-if="isWaiting" class="waiting-state">
      <div class="spinner"></div>
      <div
        class="waiting-text"
        style="font-family: 'Inter Variable', sans-serif"
      >
        Loading data...
      </div>
    </div>

    <!-- 空状态：等待结束后数据仍为空时显示 -->
    <div
      v-else-if="travelTypes.length === 0 || formattedTravelTypes.length === 0"
      class="empty-state-message"
      style="font-family: 'Inter Variable', sans-serif"
    >
      Please select a different time range or frequency
    </div>

    <!-- 图表：数据正常时显示 -->
    <div class="chart-container" v-else>
      <PieChart :option="optionAnnular" :height="'1.3375rem'"></PieChart>
    </div>
  </div>
</template>

<script>
import { fontChart } from "@/utils/echartPxToRem";
import PieChart from "@components/common/PieChart.vue";

export default {
  components: {
    PieChart,
  },
  props: {
    travelTypes: {
      type: Array,
      required: false,
      default: () => [],
    },
  },
  data() {
    return {
      isWaiting: true, // 控制等待状态（初始为true）
      waitTimer: null, // 计时器实例
      optionAnnular: {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "shadow" },
          formatter: (params) => {
            const index = params[0].dataIndex;
            const travelerType = this.formattedTravelTypes[index].travelerType;
            const realValue = this.displayData[index].realValue;
            return `${travelerType}: ${realValue}`;
          },
        },
        grid: {
          left: 270,
          right: "5%",
          top: "7%",
          bottom: "0%",
          containLabel: false,
        },
        xAxis: {
          type: "value",
          show: false,
        },
        yAxis: {
          type: "category",
          data: [],
          axisLine: { show: false },
          axisTick: { show: false },
          margin: 0,
          inverse: true,
          axisLabel: {
            align: "left",
            margin: 270,
            verticalAlign: "middle",
            color: "#232323",
            fontSize: 12,
            overflow: "truncate",
            fontWeight: "400",
          },
          boundaryGap: [0.1, 0.1],
        },
        series: [
          {
            name: "number",
            type: "bar",
            stack: "total",
            barWidth: 18,
            label: {
              show: true,
              position: "insideRight",
              formatter: (params) => {
                return this.displayData[params.dataIndex].realValue;
              },
              color: "#fff",
              fontSize: 10,
              fontWeight: "bold",
              emphasis: {
                fontSize: 12,
                fontWeight: "bold",
                color: "#fff",
              },
            },
            emphasis: {
              focus: "series",
            },
            data: [],
            itemStyle: {
              color: "#708dd1",
              borderColor: "#fff",
              borderWidth: 2,
              borderRadius: [6, 6, 6, 6],
            },
          },
        ],
      },
    };
  },
  computed: {
    formattedTravelTypes() {
      return this.travelTypes
        .filter((item) => {
          const type = item?.travelerType || "";
          return type.toUpperCase() !== "UNKNOWN" && item?.number;
        })
        .sort((a, b) => Number(b.number) - Number(a.number))
        .slice(0, 5)
        .map((item) => ({
          ...item,
          travelerType: this.formatTravelerType(item.travelerType),
        }));
    },
    totalNumber() {
      return this.formattedTravelTypes.reduce(
        (sum, item) => sum + Number(item.number),
        0
      );
    },
    displayData() {
      const total = this.totalNumber;
      return this.formattedTravelTypes.map((item) => {
        const realValue = Number(item.number);
        const realPercent = total ? (realValue / total) * 100 : 0;
        const displayValue =
          realPercent < 5 ? (total ? (total * 6) / 100 : 0) : realValue;
        return { displayValue, realValue };
      });
    },
  },
  mounted() {
    this.updateChartData();
    this.startWaitTimer(); // 初始加载时启动等待计时器
  },
  watch: {
    travelTypes: {
      handler() {
        this.updateChartData();
        this.startWaitTimer(); // 数据变化时重新启动等待计时器
      },
      deep: true,
    },
  },
  methods: {
    formatTravelerType(type) {
      if (!type || typeof type !== "string") return "";
      return type.charAt(0).toUpperCase() + type.slice(1).toLowerCase();
    },
    updateChartData() {
      if (!this.formattedTravelTypes.length) return;

      const categories = this.formattedTravelTypes.map((item, index) => {
        return `${index + 1}. ${item.travelerType}`;
      });
      const displayValues = this.displayData.map((item) => item.displayValue);

      this.optionAnnular.yAxis.data = categories;
      this.optionAnnular.series[0].data = displayValues;
    },
    // 启动等待计时器（3秒后结束等待）
    startWaitTimer() {
      if (this.waitTimer) {
        clearTimeout(this.waitTimer);
      }
      this.waitTimer = setTimeout(() => {
        this.isWaiting = false;
      }, 3000); // 保持3秒等待时间，与上一个组件一致
    },
  },
  // 组件销毁时清除计时器
  beforeDestroy() {
    if (this.waitTimer) {
      clearTimeout(this.waitTimer);
    }
  },
};
</script>

<style scoped lang="scss">
.Progress-neg-container {
  background: #fff;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  padding: 16px 24px;
  border-radius: 8px;
  border: 1px solid #cdcccc;

  .title {
    font-size: 0.125rem;
    color: #454545;
    font-weight: 600;
  }

  // 等待状态样式（与上一个组件保持一致）
  .waiting-state {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 1.3375rem;
    gap: 8px;

    .spinner {
      width: 16px;
      height: 16px;
      border: 2px solid rgba(112, 141, 209, 0.3); // 颜色匹配图表主色
      border-top-color: #708dd1; // 与柱状图颜色一致
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    .waiting-text {
      color: #999;
      font-size: 0.0972rem;
      font-family: "Inter Variable", sans-serif;
    }
  }

  .empty-state-message {
    display: flex;
    justify-content: center;
    align-items: center;
    color: #999;
    font-size: 0.0972rem;
    font-family: "Inter Variable", sans-serif;
    height: 1.3375rem;
    border-radius: 4px;
    margin: auto;
    width: 80%;
  }
}

// 加载动画（保持一致）
@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
